using UnityEngine;
using WebSocketSharp;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System.Text;
using System;

public class beController : MonoBehaviour
{
    private float rotationSpeed = 5.0f;
    private Color newColor = Color.red;

    public Transform cubeTransform;
    public GameObject[] enemyPrefabs;  // Array to store multiple enemy prefabs

    private WebSocket webSocket;
    private yuzhiti enemyGenerator;

    private void Start()
    {
        webSocket = new WebSocket("ws://192.168.43.1:8083/websocket");
        webSocket.OnMessage += OnWebSocketMessage;
        webSocket.Connect();
        Debug.Log("WebSocket connected to ws://192.168.43.1:8083/websocket");

        // Check if enemyPrefabs array is not null and not empty
        if (enemyPrefabs != null && enemyPrefabs.Length > 0 && cubeTransform != null)
        {
            enemyGenerator = GetComponent<yuzhiti>();
            if (enemyGenerator == null)
            {
                Debug.LogError("yuzhiti script not found on the same GameObject as beController. Please attach the yuzhiti script to the same GameObject.");
            }
        }
        else
        {
            Debug.LogError("enemyPrefabs array or cubeTransform is null or empty. Please check references in the Inspector.");
        }
    }

    void Update()
    {
        cubeTransform.Rotate(Vector3.up * rotationSpeed * Time.deltaTime);
    }

    private void OnWebSocketMessage(object sender, MessageEventArgs e)
    {
        string message = e.Data;
        string utf8Message = Encoding.UTF8.GetString(Encoding.Default.GetBytes(message));

        try
        {
            JObject jsonData = JObject.Parse(utf8Message);
            int messageType = Convert.ToInt32(jsonData["Type"]);

            switch (messageType)
            {
                case 1:
                    HandleNormalBarrage(jsonData);
                    break;

                case 3:
                    HandleUserJoin(jsonData);
                    break;

                case 5:
                    HandleMoveAndSkill(jsonData);
                    break;

                default:
                    Debug.Log("Unhandled message type: " + messageType);
                    break;
            }
        }
        catch (JsonReaderException ex)
        {
            Debug.LogError("Error parsing JSON: " + ex.Message);
        }

        if (!webSocket.IsAlive)
        {
            Debug.LogWarning("WebSocket connection closed, reconnecting...");
            webSocket.Connect();
            Debug.Log("WebSocket reco ws://192.168.43.1:8083/websocket");
        }
    }

    private void HandleNormalBarrage(JObject jsonData)
    {
        string barrageData = jsonData["Data"].ToString();
        JObject barrageObject = JObject.Parse(barrageData);
        string userNickname = barrageObject["User"]["Nickname"].ToString();
        string barrageContent = barrageObject["Content"].ToString();

        Debug.Log(userNickname + ": " + barrageContent);

        if (barrageContent == "c")
        {
            Renderer cubeRenderer = cubeTransform.GetComponent<Renderer>();
            cubeRenderer.material.color = newColor;
        }

        // Do not need to check "spawn_enemy" anymore, generate the enemy directly when the user joins
        // ...
    }

    private void HandleUserJoin(JObject jsonData)
    {
        string userData = jsonData["Data"].ToString();
        JObject userObject = JObject.Parse(userData);

        string username = userObject["User"]["Nickname"].ToString();
        int followerCount = Convert.ToInt32(userObject["User"]["FollowerCount"]);
        Debug.Log("User joined: " + username + " with " + followerCount + " followers");

        // 调用 yuzhiti 脚本的 GenerateRandomEnemy 方法，并传递用户名
        if (enemyGenerator != null)
        {
            Debug.Log("enemyGenerator is not null, calling GenerateRandomEnemy");
            enemyGenerator.GenerateRandomEnemy(username);
        }
    }

    private void HandleMoveAndSkill(JObject jsonData)
    {
        Debug.Log("Handling move and skill logic...");
        // Handle movement and skill logic here
        // Parse jsonData to get relevant information and apply movement logic to the corresponding character in the game
    }

    private void OnDestroy()
    {
        if (webSocket != null && webSocket.IsAlive)
        {
            webSocket.Close();
        }
    }
}
